﻿using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.Win32;
using SybaseLogRecovery.Properties;

namespace SybaseLogRecovery
{
    internal class DataBaseStatics
    {
        public static string[] GetOdbcDriverNames()
        {
            string[] odbcDriverNames = null;
            using (RegistryKey localMachineHive = Registry.LocalMachine)
            using (RegistryKey odbcDriversKey = localMachineHive.OpenSubKey(@"SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers"))
            {
                if (odbcDriversKey != null)
                {
                    odbcDriverNames = odbcDriversKey.GetValueNames();
                }
            }

            return odbcDriverNames;
        }

        public static Dictionary<string, string> GetSybaseConnectionNames()
        {
            Dictionary<string, string> connectionNames = new Dictionary<string, string>();
            Regex serverNameRegex = new Regex(@"\s*\[(?<name>[\w-]+)\][\r\n\s]*.*,(?<server>[\w\.-]+),\d{4}");
            var sybasePath = Environment.ExpandEnvironmentVariables(@"%SYBASE%");
            if (sybasePath == @"%SYBASE%" || !File.Exists(@sybasePath + @"\ini\sql.ini"))
            {
                MessageBox.Show(@"Конфигурационный файл %SYBASE%\ini\sql.ini не найден!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            var content = File.ReadAllText(@sybasePath + @"\ini\sql.ini");
            var serverNameMatches = serverNameRegex.Matches(content);
            foreach (Match serverNameMatch in serverNameMatches)
            {
                connectionNames.Add(serverNameMatch.Groups["name"].Value, serverNameMatch.Groups["server"].Value);
            }
            return connectionNames.Count == 0 ? null : connectionNames;
        }

        public static bool ConnectionCheck(string cs = null)
        {
            string cs1 = cs ?? Settings.Default.dataConnectionString;
            using (OdbcConnection connection = new OdbcConnection(cs1))
            {
                try
                {
                    connection.Open();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
                finally
                {
                    connection.Close();
                }
            }


        }
    }
}
